<template>
    <div class="w-full h-full" ref="boxRef">
        <div ref="codeEditBox" class="w-full" :style="`height:${heightValue}px`"></div>
    </div>
</template>

<script setup lang="ts">
import {nextTick, ref, toRaw} from "vue";
import * as monaco from 'monaco-editor';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'

const codeEditBox = ref()
const editor = ref()
const boxRef = ref()
const heightValue = ref()
const valueText = ref('')
// @ts-ignore
self.MonacoEnvironment = {
    getWorker: function (moduleId: string, label: string): any {
        if (label === 'json') {
            return new jsonWorker()
        }
        if (['css', 'scss', 'less'].includes(label)) {
            return new cssWorker()
        }
        if (['html', 'handlebars', 'razor'].includes(label)) {
            return new htmlWorker()
        }
        if (['typescript', 'javascript'].includes(label)) {
            return new tsWorker()
        }
        return EditorWorker;
    }
}

const init = (value = '', language = "java") => {
    heightValue.value = boxRef.value.clientHeight
    if (!editor.value) {
        editor.value = monaco.editor.create(codeEditBox.value, {
            value: value, // 编辑器初始显示文字
            language: language, // 语言支持自行查阅demo
            automaticLayout: true, // 自适应布局
            theme: 'vs-dark', // 官方自带三种主题vs, hc-black, or vs-dark
            foldingStrategy: 'indentation',
            renderLineHighlight: 'all', // 行亮
            selectOnLineNumbers: true, // 显示行号
            minimap: {
                enabled: false,
            },
            readOnly: false, // 只读
            fontSize: 16, // 字体大小
            scrollBeyondLastLine: false, // 取消代码后面一大段空白
            overviewRulerBorder: false, // 不要滚动条的边框
        })
    } else {
        changeLanguage(language)
        setData(value)
    }


}
/*
   更改编程语言
 */
const changeLanguage = (value: string) => {
    monaco.editor.setModelLanguage(editor.value.getModel(), value)
}
/*
获取数据
 */
const getData = () => {
    return toRaw(editor.value).getValue()
}
/**
 * 设置数据
 * @param value
 */
const setData = (value: string) => {
    toRaw(editor.value).setValue(value)
}
defineExpose({init, changeLanguage, getData})
</script>

<style scoped>

</style>